import 'package:flutter/material.dart';
import 'package:xindong/common/xindong_define.dart';

// 飘屏动画容器
// child 组件（要自带尺寸）
class XinDongPiaoPingAnimationContainer extends StatefulWidget {
  final int milliseconds;
  final Widget child;

  const XinDongPiaoPingAnimationContainer({Key? key, required this.milliseconds, required this.child})
      : super(key: key);

  @override
  State<XinDongPiaoPingAnimationContainer> createState() => _XinDongPiaoPingAnimationContainerState();
}

class _XinDongPiaoPingAnimationContainerState extends State<XinDongPiaoPingAnimationContainer>
    with SingleTickerProviderStateMixin {
  late AnimationController animationController;
  Animation<double>? positionAnimation;
  Animation<double>? positionEndAnimation;
  Animation<double>? fadeAnimation;
  bool isShow = true;

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(vsync: this, duration: Duration(milliseconds: widget.milliseconds));
  }

  void loadAnimation() {
    positionAnimation = Tween(
      begin: screenWidth,
      end: 0.0,
    ).animate(CurvedAnimation(
      parent: animationController,
      curve: const Interval(0.0, 0.3, curve: Curves.easeOutQuint),
    ));

    positionEndAnimation = Tween(
      begin: 0.0,
      end: -screenWidth,
    ).animate(CurvedAnimation(
      parent: animationController,
      curve: const Interval(0.9, 1.0, curve: Curves.easeInToLinear),
    ));

    fadeAnimation = Tween(
      begin: 1.0,
      end: 0.0,
    ).animate(CurvedAnimation(
      parent: animationController,
      curve: const Interval(0.9, 1.0, curve: Curves.easeInToLinear),
    ));
    animationController.reset();
    animationController.forward();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    loadAnimation();
    return GestureDetector(
      onHorizontalDragEnd: (a) {
        setState(() {
          isShow = false;
        });
      },
      child: AnimatedBuilder(
        animation: animationController,
        builder: (BuildContext context, Widget? child) {
          if (positionAnimation == null || positionEndAnimation == null || fadeAnimation == null || isShow == false) {
            return const SizedBox();
          }
          return Stack(
            clipBehavior: Clip.none,
            children: [
              Positioned(
                left: animationController.value < 0.5 ? positionAnimation!.value : positionEndAnimation!.value,
                child: FadeTransition(
                  opacity: fadeAnimation!,
                  child: widget.child,
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
